package com.yvan.http;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class HttpSession {

    private static final Logger LOGGER = LoggerFactory.getLogger("curl");

    private final YvanCookieJar cookieJar;

    public static HttpSession create() {
        return new HttpSession(new YvanCookieJar());
    }

    public HttpSession(YvanCookieJar cookieJar) {
        this.cookieJar = cookieJar;
    }

    public Curl curl() {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new LogIntercaptor())
                .addNetworkInterceptor(new NetworkIntercaptor())
                .cookieJar(this.cookieJar)
                .build();
        return new Curl(client, LOGGER);
    }

    public CookieJar cookie() {
        return this.cookieJar;
    }

    static class NetworkIntercaptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            LOGGER.debug("* " + chain.connection());
            LOGGER.debug("* " + chain.request().method() + " " + request.url().url().getFile() + " " + chain.connection().protocol().toString());

            for (String name : request.headers().names()) {
                LOGGER.debug("> " + name + ": " + request.header(name));
            }

            Response response = chain.proceed(request);

            LOGGER.debug(String.format("* received %d bytes cost %dms",
                    response.body().contentLength(),
                    response.receivedResponseAtMillis() - response.sentRequestAtMillis()));

            LOGGER.debug("< " + response.protocol() + " " + response.code());
            for (String name : response.headers().names()) {
                LOGGER.debug("< " + name + ": " + response.header(name));
            }

            return response;
        }
    }

    static class LogIntercaptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            LOGGER.debug("* connect to " + request.url());
            return chain.proceed(request);
        }
    }
}
